package com.taa.domain.trade.service.order;

import com.taa.domain.trade.adapter.repository.ITradeRepository;
import com.taa.domain.trade.model.entity.OrderEntity;
import com.taa.domain.trade.model.entity.ProductEntity;
import com.taa.domain.trade.service.AbstractOrderService;
import com.taa.domain.trade.service.chain.IValidationChain;
import com.taa.domain.trade.service.chain.factory.DefaultChainFactory;
import com.taa.domain.trade.service.discount.IDiscountStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: taa
 * @Desc: 订单处理默认实现
 * @Create: 2025-06-02 13:55
 **/
@Slf4j
@Service
public class DefaultOrderService extends AbstractOrderService {
    
    public DefaultOrderService(ITradeRepository repository, DefaultChainFactory defaultChainFactory, Map<String, IDiscountStrategy> discountStrategyGroup) {
        super(repository, defaultChainFactory, discountStrategyGroup);
    }

    @Override
    public boolean validate(String userName, List<Long> productIdList) {
        IValidationChain validationChain = defaultChainFactory.getChain();
        return validationChain.validate(userName, productIdList);
    }

    @Override
    public BigDecimal applyDiscount(ProductEntity productEntity) {
        BigDecimal originalPrice = productEntity.getOriginalPrice();
        BigDecimal discountPrice = originalPrice;
        if (productEntity.getStrategyEntityList() != null && !productEntity.getStrategyEntityList().isEmpty()) {
            for (ProductEntity.StrategyEntity strategyEntity : productEntity.getStrategyEntityList()) {
                IDiscountStrategy discountStrategy = discountStrategyGroup.get(strategyEntity.getStrategyName());
                BigDecimal calculate = discountStrategy.calculate(originalPrice, strategyEntity.getStrategyValue());
                discountPrice = discountPrice.compareTo(calculate) >= 0 ? calculate : discountPrice;
            }
        }
        return discountPrice;
    }

    @Override
    public boolean reduceStock(List<Long> productIdList) {
        log.info("订单商品库存扣减 reduceStock productIdList: {}", productIdList);
        return repository.reduceStock(productIdList);
    }

    @Override
    public OrderEntity generateOrder(String userName, List<ProductEntity> productEntityList, BigDecimal totalOriginalPrice, BigDecimal totalDiscountPrice) {
        log.info("订单生成 generateOrder userName: {}, productIdList: {}, totalOriginalPrice: {}, totalDiscountPrice: {}", userName, productEntityList, totalOriginalPrice, totalDiscountPrice);
        return repository.generateOrder(userName, productEntityList, totalOriginalPrice, totalDiscountPrice);
    }

    @Override
    public List<OrderEntity> queryOrderByUserName(String userName) {
        return repository.queryOrderByUserName(userName);
    }
}

